package com.lemon.cloud.security.component;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lemon.cloud.comm.model.ResultCode;
import com.lemon.cloud.comm.model.ResultMsg;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 客户端异常处理 AuthenticationException 不同细化异常处理
 *
 * @author HuangDS
 */
@SuppressWarnings("ALL")
@Slf4j
@AllArgsConstructor
@Component
public class OAuth2ResourceExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;
    private final MessageSource messageSource;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType(ContentType.JSON.getValue());
        ResultMsg<String> result = new ResultMsg<>(ResultCode.NO_PERMISSION.getCode(), ResultCode.NO_PERMISSION.getMsg(), authException.getMessage());
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        if (authException != null) {
            result.setMsg("error");
            result.setData(authException.getMessage());
        }
        //令牌过期处理
        if (authException instanceof CredentialsExpiredException
                || authException instanceof InsufficientAuthenticationException) {
            result.setCode(ResultCode.TOKEN_EXPIRE.getCode());
            result.setMsg(ResultCode.TOKEN_EXPIRE.getMsg());
        }
        if (authException instanceof UsernameNotFoundException) {
            result.setCode(ResultCode.USERNAME_OR_PASSWORD_ERROR.getCode());
            result.setMsg(ResultCode.USERNAME_OR_PASSWORD_ERROR.getMsg());
        }

        if (authException instanceof BadCredentialsException) {
            result.setCode(ResultCode.BAD_CREDENTIALS_ERROR.getCode());
            result.setMsg(ResultCode.BAD_CREDENTIALS_ERROR.getMsg());
        }

        // 针对令牌过期返回特殊的 424
        if (authException instanceof InvalidBearerTokenException
                || authException instanceof InsufficientAuthenticationException) {
            response.setStatus(org.springframework.http.HttpStatus.FAILED_DEPENDENCY.value());
            result.setMsg(this.messageSource.getMessage("OAuth2ResourceOwnerBaseAuthenticationProvider.tokenExpired",
                    null, LocaleContextHolder.getLocale()));
        }
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
